package com.epfresh.global;


import java.util.HashMap;

/**
 * @author wangzhanghuan
 * @version 1.0
 * @date create 2018/1/24
 * @Description
 * @Project EpfreshSupplier
 * @Package com.epfresh.global
 */

public class CartHelper {

    public interface CartHelperTools {
        //获取唯一的key
        String getUniqueKey();

        //重置数量
        void setCount(double cnt);
    }


    //用于解决连续加入购物车问题
    //加入购物车针对一个商品请求加锁
    private HashMap<String, Boolean> mapReqLock = new HashMap<>();
    private HashMap<String, Boolean> mapReqStatus = new HashMap<>();

    //存储最新准备加入购物车的数量
    private HashMap<String, CartHelperTools> mapGoods = new HashMap<>();

    //存储购物车的数量
    private HashMap<String, Double> mapGoodsLastCount = new HashMap<>();
    //----------------------------------------------------------------------------//

    public void resetHelper() {
        mapGoods.clear();
        mapGoodsLastCount.clear();
        mapReqLock.clear();
    }

    //检查是否可以请求
    public boolean checkIsCartRequesting(CartHelperTools cartHelperTools) {

        if (cartHelperTools != null) {
            String key = cartHelperTools.getUniqueKey();
            Boolean aBoolean = mapReqLock.get(key);
            //是否在请求中,true请求中,不予请求
            if (aBoolean == null || !aBoolean) {
                mapReqLock.put(key, true);
                mapGoods.remove(key);
                //可以请求
                return false;
            } else {
                //如果正在请求放入map缓存
                mapGoods.put(key, cartHelperTools);
                return true;
            }
        }

        return true;
    }

    public boolean isRequesting(String key){
        Boolean aBoolean = mapReqStatus.get(key);
        //是否在请求中,true请求中,不予请求

        return aBoolean == null?false:aBoolean;
    }
    public void updateRequest(String key){

        mapReqStatus.put(key,true);
    }
    //添加购物车成功,判断是否有缓存请求
    public CartHelperTools responseCartSuccess(CartHelperTools goods, double count) {
        String key = goods.getUniqueKey();
/*        if (count > 0)/////这个地方的代码，数量的set应该是判断当前的执行队列是否还有请求转移下面这行代码
        goods.setCount(count);*/
        mapReqLock.put(key, false);
        mapGoodsLastCount.put(key, count);
        CartHelperTools g = mapGoods.get(key);
        mapReqStatus.remove(key);
        if (g != null) {
            //执行队列请求
            return g;
        } else {
            //清除缓存数量
            goods.setCount(count);
            mapGoodsLastCount.remove(key);
            return null;
        }
    }

    //添加购物车失败,清除key对应的所有缓存请求
    public void responseCartFail(CartHelperTools goods) {
        String key = goods.getUniqueKey();
        mapReqLock.put(key, false);
        mapGoods.remove(key);
        Double count = mapGoodsLastCount.get(key);
        count = count == null ? 0 : count;
        goods.setCount(count);
        mapGoodsLastCount.remove(key);
        mapReqStatus.remove(key);
    }



}
